package com.credit.service;

import java.math.BigDecimal;
import java.util.Map;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchDataTransform;
import org.springside.modules.persistence.SearchFilter;

import com.credit.entity.CreditCoinRecord;
import com.credit.entity.CreditPaymentOrder;
import com.credit.entity.CreditUserInfo;
import com.credit.repository.CreditCoinDao;
import com.credit.util.CodeValueUtil;
import com.credit.util.CoinUtil;
import com.credit.util.ParamsConstant;

@Service("creditCoinService")
@Transactional
public class CreditCoinService {
	@Autowired
	private CreditCoinDao creditCoinDao;
	@Autowired
	private UserService userService;
	@Autowired
	private CreditPaymentOrderService creditPaymentOrderService;

	public Page<CreditCoinRecord> getCoinListPage(Map<String, Object> searchParams, int pageNumber, Integer pageSize,
			String sortType, Map<String, SearchDataTransform> dataTyps) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (dataTyps != null) {
			SearchDataTransform.dateTypeTransform(filters, dataTyps);
		}
		Specification<CreditCoinRecord> spec = DynamicSpecifications.bySearchFilter(filters.values(), CreditCoinRecord.class);
		return creditCoinDao.findAll(spec, pageRequest);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else {
			sort = new Sort(Direction.DESC, sortType);
		}
		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	public void addCoinRecord(CreditCoinRecord coinRecord) {
		creditCoinDao.save(coinRecord);
		
	}

	public void increase(CreditPaymentOrder paymentOrder, Integer coins) {
		
		//支付订单完成
		paymentOrder.setStatus("2");
		creditPaymentOrderService.updatePaymentOrder(paymentOrder);
		
		//为用户添加金币
		CreditUserInfo userInfo = userService.findUserById(paymentOrder.getPayUserId());
		userInfo.setCoin(userInfo.getCoin()+coins);
		userService.updateUserInfo(userInfo);
		
		//添加金币记录
		CoinUtil.addCoinRecord(String.valueOf(CodeValueUtil.USERTYPE_MANAGER), userInfo.getId(), coins, "购买"+coins+"枚金币",paymentOrder.getAmount());
	}
}
